//
//  IGAFNetworking.m
//  iGameApp
//
//  Created by Yf66 on 16/1/11.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IGAFNetworking.h"

@implementation IGAFNetworking




+ (void)requestWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic metho:(RequestType )method finish:(Finish)finish error:(Error)requestError {
    //  parDic是传的参数
    
    NSString *requestStr = urlString;
    
    if (parDic.count != 0) {
        NSMutableArray *strArray = [NSMutableArray array];
        for (NSString *key in parDic) {
            NSString *str = [NSString stringWithFormat:@"%@=%@",key,parDic[key]];
            [strArray addObject:str];
        }
        NSString *parString = [strArray componentsJoinedByString:@"&"];
        requestStr = [NSString stringWithFormat:@"%@&%@",urlString,parString];
    }
    
    NSURL *url = [NSURL URLWithString:requestStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    NSURLSessionConfiguration *configure = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFHTTPSessionManager *mgr = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configure];
    NSURLSessionDataTask *dataTask = [mgr dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error == nil) {
            finish(responseObject);
        } else {
            requestError(error);
        }
    }];
    [dataTask resume];
}

+ (void)newRequestWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic method:(RequestType)method finish:(Finish)finish error:(Error)error
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    if (method == POST) {
        [request setHTTPMethod:@"POST"];
        if (parDic.count != 0) {
            NSMutableArray *strArray = [NSMutableArray array];
            for (NSString *key in parDic) {
                NSString *str = [NSString stringWithFormat:@"%@=%@",key,parDic[key]];
                [strArray addObject:str];
            }
            NSString *parString = [strArray componentsJoinedByString:@"&"];
            [request setHTTPBody:[parString dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            finish(dic);  // 函数的调用
        }else{
            error(connectionError); // 函数的调用
        }
    }];
}


@end
